import axios from 'axios'
import { MessageBox, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import apiConst from '@/common/js/apiConst'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authentication'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

let needTip = true
// response interceptor
service.interceptors.response.use(
  /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

  /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
  response => {
    const res = response.data
    if (res.status === undefined && response.status === apiConst.STATUS.STATUS_OK) {
      return response
    }
    if (res.status === apiConst.STATUS.STATUS_UNAUTHORIZED || res.status === apiConst.STATUS.STATUS_FORBIDDEN) {
      // to re-login
      console.log(`repeat err000：${res.message}`)
      if (needTip) {
        needTip = !needTip
        MessageBox.confirm('登录信息已失效，请重新登录', '确认', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, () => {
          needTip = !needTip
        })
      } else {
        console.log(`repeat err：${res.message}`)
      }
      return Promise.reject(new Error(`:${res.message || res.error || 'Error'}`))
    } else if (res.status !== apiConst.STATUS.STATUS_OK) {
      console.log(`response interceptor: ${JSON.stringify(res)}`)
      return Promise.reject(new Error(':' + (res.message || res.error || 'Error')))
    } else {
      return res
    }
  },
  error => {
    console.log('unknown err：' + error) // for debug
    Notification.error({
      title: '异常提示',
      message: `未知异常：${error.message || error.error || 'ERROR'}`,
      duration: 5 * 1000
    })
    // return Promise.reject(new Error(''))
  }
)

export default service
